package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {
    @Autowired
    private AddressService addressService;
    //查询所有
    @GetMapping("/address/list")
    public ResultInfo findList(){
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }
    //增加地址
    @PostMapping("/address")
    public ResultInfo saveAdress(@RequestBody Address address){
        addressService.saveAdress(address);
        return ResultInfo.success(null);
    }
    //更改默认地址
    @PutMapping("/address/default")
    public ResultInfo defaultAddress(@RequestBody Map<String, Long> map){
        Long id = map.get("id");
        addressService.defaultAddress(id);
        return ResultInfo.success(null);
    }
    //获取默认地址
    @GetMapping("/address/default")
    public ResultInfo findDefault(){
        Address address = addressService.findDefault();
        if (address != null) {
            //设置默认地址
            return ResultInfo.success(address);
        } else {
            //没有设置默认地址
            return ResultInfo.error("没有默认地址");
        }
        //return ResultInfo.success(address);
    }
    //修改地址回显
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Address address = addressService.findById(id);
        return ResultInfo.success(address);
    }
    //更新地址
    @PutMapping("/address")
    public ResultInfo updateAddress(@RequestBody Address address){
        addressService.updateAddress(address);
        return ResultInfo.success(null);
    }
    //删除
    @DeleteMapping("/address")
    public ResultInfo deleteAddress(Long ids){
        addressService.deleteAddress(ids);
        return ResultInfo.success(null);
    }
}
